package com.fount4j.generator.introspect;

import com.fount4j.generator.config.MapperConfig;
import com.fount4j.generator.context.GeneratorContext;
import com.fount4j.generator.exception.GenerateException;
import com.fount4j.generator.info.MapperInfo;
import com.fount4j.generator.util.GeneratorFileUtils;
import com.fount4j.generator.util.StringUtils;

import java.io.File;
import java.io.IOException;

/**
 * 映射文件解析器
 *
 * @author Morven 2016/12/22
 */
public class MapperIntrospector implements BaseIntrospector {
    /**
     * 解析映射文件
     *
     * @param context 生成器上下文
     */
    @Override
    public void introspect(GeneratorContext context) {
        context.setMapperInfo(new MapperInfo());

        introspectName(context);
        introspectFile(context);
    }

    /**
     * 解析文件路径
     *
     * @param context 生成器上下文
     */
    private void introspectFile(GeneratorContext context) {
        MapperConfig mapperConfig = context.getMapperConfig();
        String packageName = context.getTableConfig().getMapperPackage();
        if (StringUtils.isBlank(packageName)) {
            packageName = mapperConfig.getPackageName();
        }
        File file = GeneratorFileUtils
                .getFile(mapperConfig.getResourcePath(), packageName, context.getMapperInfo().getName() + ".xml");
        context.getMapperInfo().setFile(file);
        try {
            context.getMapperInfo().setCustomContent(GeneratorFileUtils.getCustomContent(file));
        } catch (IOException e) {
            throw new GenerateException("读取文件自定义内容出错: " + file, e);
        }
    }

    /**
     * 解析文件名
     *
     * @param context 生成器上下文
     */
    protected void introspectName(GeneratorContext context) {
        context.getMapperInfo().setName(context.getEntityInfo().getName() + context.getMapperConfig().getNameSuffix());
    }
}
